package com.yungu.swift.system.sys.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.yungu.swift.assets.driver.service.CarService;
import com.yungu.swift.assets.driver.service.DriverService;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.base.mapper.IMapper;
import com.yungu.swift.base.model.PageVo;
import com.yungu.swift.base.service.impl.BaseServiceImpl;
import com.yungu.swift.constants.CommonConstant;
import com.yungu.swift.order.service.OrderFareService;
import com.yungu.swift.system.sys.dao.SysCompanyMapper;
import com.yungu.swift.system.sys.dao.SysRegionalAgentMapper;
import com.yungu.swift.system.sys.model.dto.*;
import com.yungu.swift.system.sys.model.param.AdminAgentPageParam;
import com.yungu.swift.system.sys.model.vo.BusinessDetailVo;
import com.yungu.swift.system.sys.model.vo.BusinessVo;
import com.yungu.swift.system.sys.model.vo.RegionalAgentDetailVo;
import com.yungu.swift.system.sys.model.vo.RegionalAgentVo;
import com.yungu.swift.system.sys.service.*;
import com.yungu.swift.utils.MapUtils;
import com.yungu.swift.utils.Md5Utils;
import com.yungu.swift.utils.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * SystemRegionalAgentServiceImpl
 **/
@Service
public class SysRegionalAgentServiceImpl extends BaseServiceImpl<SysRegionalAgentDto> implements SysRegionalAgentService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysCompanyMapper sysCompanyMapper;
    @Autowired
    private SysRegionalAgentMapper systemRegionalAgentMapper;
    @Autowired
    private SysBusinessOrganizationService sysBusinessOrganizationService;

    @Reference
    private DriverService driverService;
    @Autowired
    private SysCompanyService sysCompanyService;
    @Reference
    private CarService carService;
    @Reference
    private OrderFareService orderFareService;
    @Reference
    private SysAccountAgentService sysAccountAgentService;

    @Override
    protected IMapper<SysRegionalAgentDto> getMapper() {
        return systemRegionalAgentMapper;
    }

    @Override
    public ResponseData<PageVo<RegionalAgentVo>> queryPageVo(AdminAgentPageParam agentPageParam) {
        PageBounds pageBounds = new PageBounds(agentPageParam.getPageNum(), agentPageParam.getPageSize());
        PageList<RegionalAgentVo> pageList = systemRegionalAgentMapper.queryPageVo(BeanMap.create(agentPageParam), pageBounds);
        // 不显示小件业务
        pageList.forEach(regionalAgentVo -> {
            List<BusinessVo> businesses = regionalAgentVo.getBusinesses();
            if (CollectionUtils.isNotEmpty(businesses)) {
                List<BusinessVo> businessVos = businesses.stream().filter(businessVo -> businessVo.getType() !=
                        CommonConstant.BUSINESS_TYPE_PARCEL).collect(Collectors.toList());
                regionalAgentVo.setBusinesses(businessVos);
            }
        });
        PageVo<RegionalAgentVo> pageVo = new PageVo(agentPageParam.getPageNum(), agentPageParam.getPageSize(), pageList.getPaginator().getTotalCount());
        pageVo.setItems(pageList);
        return ResponseData.buildSuccessResponse(pageVo);
    }

    @Override
    public ResponseData<RegionalAgentDetailVo> detail(String regionalAgentUuid, String appid) {
        List<SysRegionalAgentDto> result = systemRegionalAgentMapper.list(MapUtils.build("uuid", regionalAgentUuid));
        if (CollectionUtils.isEmpty(result)) {
            return ResponseData.buildSuccessResponse(null);
        }
        SysRegionalAgentDto regionalAgentDto = result.get(0);
        RegionalAgentVo regionalAgentVo = new RegionalAgentVo();
        BeanUtils.copyProperties(regionalAgentDto, regionalAgentVo);
        int driverCount = driverService.getCountAdmin(null, regionalAgentUuid, null).getData();
        int orderCount = driverService.getOrderCount(null, regionalAgentUuid, null).getData();
        Map<String, Object> build = MapUtils.build(4);
        build.put("agentUuid", regionalAgentUuid);
        build.put("appid", appid);
        //营业额
        Double totalOrder = this.orderFareService.getIncome(build).getData();
        //车辆总数
        int carCount = carService.getCarCount(null, regionalAgentUuid, null).getData();
        RegionalAgentDetailVo detailBean = new RegionalAgentDetailVo();
        detailBean.setRegionalAgentVo(regionalAgentVo);
        detailBean.setCarCount(carCount);
        detailBean.setDriverCount(driverCount);
        detailBean.setTotalOrder(totalOrder);
        detailBean.setOrderCount(orderCount);
        ResponseData<List<BusinessDetailVo>> listResponseData = sysBusinessOrganizationService.getBusinessDetail(regionalAgentUuid, null);
        if (listResponseData.isSuccess() && CollectionUtils.isNotEmpty(listResponseData.getData())) {
            List<BusinessDetailVo> businesses = listResponseData.getData();
            // 跨城小件不作为单独业务
            detailBean.setBusinesses(businesses.stream().filter(businessDetailVo -> businessDetailVo.getType()
                    != CommonConstant.BUSINESS_TYPE_PARCEL).collect(Collectors.toList()));
        }
        return ResponseData.buildSuccessResponse(detailBean);
    }

    @Override
    public ResponseData<Boolean> changeStatus(String uuid, int status, String userUuid) {
        //检索是否存在
        SysRegionalAgentDto dto = this.systemRegionalAgentMapper.list(MapUtils.build("uuid", uuid)).get(0);
        if (dto == null) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "检索失败，未检索到代理商业务数据");
        }
        //关闭
        if (status == CommonConstant.STATUS_CLOSED) {
            //判断代理商是否有开通的公司，有就不允许关闭
            Map<String, Object> params = MapUtils.build(4);
            params.put("regionalAgentUuid", uuid);
            params.put("status", CommonConstant.STATUS_OPENED);
            List<SysCompanyDto> companyDtos = this.sysCompanyMapper.list(params);
            if (companyDtos.size() > 0) {
                return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "该代理商还有未关闭的公司，不允许关闭该代理商");
            }
            SysRegionalAgentDto upddto = new SysRegionalAgentDto();
            upddto.setUuid(dto.getUuid());
            upddto.setStatus(CommonConstant.STATUS_CLOSED);
            upddto.setUpdateBy(userUuid);
            return ResponseData.buildSuccessResponse("关闭代理商成功", systemRegionalAgentMapper.edit(upddto) > 0);
        }
        //开通
        if (status == CommonConstant.STATUS_OPENED) {
            SysRegionalAgentDto upddto = new SysRegionalAgentDto();
            upddto.setUuid(dto.getUuid());
            upddto.setStatus(CommonConstant.STATUS_OPENED);
            upddto.setUpdateBy(userUuid);
            return ResponseData.buildSuccessResponse("更新区域代理状态成功", this.systemRegionalAgentMapper.edit(upddto) > 0);
        }
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "更新区域代理状态失败");
    }


    @Override
    public ResponseData<Boolean> add(SysRegionalAgentDto sysRegionalAgentDto) {
        //检验，账户名称唯一
        ResponseData<SysUserDto> responseData = sysUserService.get(MapUtils.build("userAccount", sysRegionalAgentDto.getName()));
        if (responseData.isSuccess() && responseData.getData() != null) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "账户名：" + sysRegionalAgentDto.getName() + "已经被注册了");
        }
        try {
            //新增代理
            systemRegionalAgentMapper.add(sysRegionalAgentDto);
            //同步新增代理账号
            SysAccountAgentDto sysAccountAgentDto = new SysAccountAgentDto();
            sysAccountAgentDto.setUuid(sysRegionalAgentDto.getUuid());
            sysAccountAgentDto.setAppid(sysRegionalAgentDto.getAppid());
            sysAccountAgentDto.setAccountName(sysRegionalAgentDto.getName());
            sysAccountAgentDto.setCashBalance(BigDecimal.ZERO);
            sysAccountAgentDto.setCouponAccumulate(BigDecimal.ZERO);
            sysAccountAgentDto.setRefundAccumulate(BigDecimal.ZERO);
            sysAccountAgentDto.setRewardAccumulate(BigDecimal.ZERO);
            sysAccountAgentDto.setStatus(1);
            sysAccountAgentDto.setCreateOn(new Date());
            sysAccountAgentDto.setCreateBy(sysRegionalAgentDto.getCreateBy());
            sysAccountAgentService.add(sysAccountAgentDto);

            //新增代理管理员账号
            SysUserDto sysUserDto = new SysUserDto();
            sysUserDto.setUuid(StringUtils.buildUUID());
            sysUserDto.setUserName(sysRegionalAgentDto.getName());
            sysUserDto.setUserAccount(sysRegionalAgentDto.getName());
            sysUserDto.setPassword(Md5Utils.encode("Xdkj123456*"));
            sysUserDto.setFirstLogin(0);
            sysUserDto.setUserType(SysUserDto.USER_TYPE_PRIMARY);
            sysUserDto.setUserRole(SysRoleDto.DEFAULT_ROLE_AGENT);
            sysUserDto.setAppid(sysRegionalAgentDto.getAppid());
            sysUserDto.setAgentUuid(sysRegionalAgentDto.getUuid());
            sysUserDto.setStatus(SysUserDto.STATUS_NORMAL);
            sysUserDto.setResetPasswordDate(new Date());
            sysUserDto.setUserMobile(sysRegionalAgentDto.getResponsibleMobile());
            sysUserDto.setCreateOn(new Date());
            sysUserService.add(sysUserDto);
            return ResponseData.buildSuccessResponse("新增成功", Boolean.TRUE);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "新增失败");
    }

    @Override
    public ResponseData<List<SysRegionalAgentDto>> findAgentByBusinessType(Map<String, Object> map) {
        return ResponseData.buildSuccessResponse(systemRegionalAgentMapper.findAgentByBusinessType(map));
    }

}